package com.googlecode.cswish.struts.conversion;

import javax.annotation.Resource;

import com.googlecode.cswish.model.PageElement;
import com.googlecode.cswish.model.PropertyInfo;
import com.googlecode.cswish.model.TextModel;
import com.googlecode.cswish.struts.Invoker;
import com.googlecode.cswish.struts.RestAction;
import com.googlecode.cswish.util.OgnlExUtil;

/**
 * Convert common attributes to PageElement
 * 	 
 * @author jerry.feng Date: 2009-1-13
 */
public abstract class CommonElementConverter implements ElementConverter {

	@Resource
	private OgnlExUtil ognlExUtil;
	
	public PageElement convert(ConversionContext context) {
		PageElement pageElement = new PageElement(ognlExUtil);
		PropertyInfo propertyInfo = context.getPropertyInfo();
		Invoker invoker = context.getInvoker();
		pageElement.setShortName(propertyInfo.getName());
		boolean isAdd = RestAction.isCreate(null, invoker.methodName);
		boolean isAddOrUpdate = isAdd || RestAction.isUpdate(null, invoker.methodName);
		boolean isRequired = isAddOrUpdate && !propertyInfo.isNullable();
		pageElement.setRequired(isRequired);
		pageElement.setLength(propertyInfo.getLength());
		boolean isRead = RestAction.isRead(null, invoker.methodName);
		if (isRead) {
			pageElement.setTextModel(TextModel.TRUE);
		}
		return pageElement;
	}
}
